import cv2
from scipy import misc
import random
import math
import collections
import numpy as np
import numbers

#[深度学习-部分数据增强python代码实现](https://www.cnblogs.com/dxscode/p/11733311.html)
class RandScale(object):
    # Randomly resize image & label with scale factor in [scale_min, scale_max]
    def __init__(self, scale, aspect_ratio=None):
        assert (isinstance(scale, collections.Iterable) and len(scale) == 2)
        if isinstance(scale, collections.Iterable) and len(scale) == 2 \
                and isinstance(scale[0], numbers.Number) and isinstance(scale[1], numbers.Number) \
                and 0 < scale[0] < scale[1]:
            self.scale = scale
        else:
            raise (RuntimeError("segtransform.RandScale() scale param error.\n"))
        if aspect_ratio is None:
            self.aspect_ratio = aspect_ratio
        elif isinstance(aspect_ratio, collections.Iterable) and len(aspect_ratio) == 2 \
                and isinstance(aspect_ratio[0], numbers.Number) and isinstance(aspect_ratio[1], numbers.Number) \
                and 0 < aspect_ratio[0] < aspect_ratio[1]:
            self.aspect_ratio = aspect_ratio
        else:
            raise (RuntimeError("segtransform.RandScale() aspect_ratio param error.\n"))

    def __call__(self, image):
        temp_scale = self.scale[0] + (self.scale[1] - self.scale[0]) * random.random()
        print(temp_scale)
        temp_aspect_ratio = 1.0
        if self.aspect_ratio is not None:
            temp_aspect_ratio = self.aspect_ratio[0] + (self.aspect_ratio[1] - self.aspect_ratio[0]) * random.random()
            print(temp_aspect_ratio)
            temp_aspect_ratio = math.sqrt(temp_aspect_ratio)
            print(temp_aspect_ratio)
        scale_factor_x = temp_scale * temp_aspect_ratio
        scale_factor_y = temp_scale / temp_aspect_ratio
        image = cv2.resize(image, None, fx=scale_factor_x, fy=scale_factor_y, interpolation=cv2.INTER_LINEAR)
        return image

def _distort(image):
    def _convert(image, alpha=1, beta=0):
        tmp = image.astype(float) * alpha + beta
        tmp[tmp < 0] = 0
        tmp[tmp > 255] = 255
        image[:] = tmp

    image = image.copy()

    if random.randrange(2):
        _convert(image, beta=random.uniform(-32, 32))

    if random.randrange(2):
        _convert(image, alpha=random.uniform(0.5, 1.5))

    image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

    if random.randrange(2):
        tmp = image[:, :, 0].astype(int) + random.randint(-18, 18)
        tmp %= 180
        image[:, :, 0] = tmp

    if random.randrange(2):
        _convert(image[:, :, 1], alpha=random.uniform(0.5, 1.5))

    image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)

    return image

def random_crop(img, scale=[0.8, 1.0], ratio=[3. / 4., 4. / 3.], resize_w=300, resize_h=500):
    """
    随机裁剪
    :param img:
    :param scale: 缩放
    :param ratio:
    :param resize_w:
    :param resize_h:
    :return:
    """
    aspect_ratio = math.sqrt(np.random.uniform(*ratio))
    w = 1. * aspect_ratio
    h = 1. / aspect_ratio
    src_h, src_w = img.shape[:2]
    bound = min((float(src_w) / src_h) / (w ** 2),
                (float(src_h) / src_w) / (h ** 2))
    scale_max = min(scale[1], bound)
    scale_min = min(scale[0], bound)
    target_area = src_h * src_w * np.random.uniform(scale_min,
                                                    scale_max)
    target_size = math.sqrt(target_area)
    w = int(target_size * w)
    h = int(target_size * h)
    i = np.random.randint(0, src_w - w + 1)
    j = np.random.randint(0, src_h - h + 1)
    img = img[j:j + h, i:i + w]
    img = cv2.resize(img, (resize_w, resize_h))
    return img

image = r"f:\bigphoto\monkey\monkey.jpg"
img = misc.imread(image)
print(f'origin_img: {img.shape}')
img = random_crop(img)
print(f"result_img: {img.shape}")
cv2.imshow('s',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

